<template>
  <div>
    <BasicModal
      v-bind="$attrs"
      v-model:visible="showContract"
      :title="isEdit == true ? '编辑合同记录' : '添加合同记录'"
      @ok="onSubmit"
    >
      <Form
        class="form_box"
        ref="formRef"
        :model="formState"
        :rules="rules"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 14 }"
      >
        <FormItem label="合同金额" name="amount">
          <Input v-model:value="formState.amount" placeholder="请输入合同金额" type="number" />
        </FormItem>
        <FormItem label="签订时间" name="signDate">
          <DatePicker
            :format="'YYYY-MM-DD'"
            valueFormat="YYYY-MM-DD"
            v-model:value="formState.signDate"
          />
        </FormItem>
        <FormItem label="签订甲方" name="firstParty">
          <Input v-model:value="formState.firstParty" placeholder="请输入签订甲方" />
        </FormItem>
        <FormItem label="资质公司编号" name="licenseCompanyId">
          <Select
            allowClear
            v-model:value="formState.licenseCompanyId"
            placeholder="请选择资质公司编号"
          >
            <SelectOption v-for="(item, index) in allLicense" :value="item.id" :key="index">{{
              item.name
            }}</SelectOption>
          </Select>
        </FormItem>
        <FormItem label="附件" name="url">
          <Upload
            :multiple="true"
            :before-upload="beforeUpload"
            :file-list="formState.url"
            @change="handleChange"
          >
            <a-button>
              <upload-outlined></upload-outlined>
              上传附件
            </a-button>
          </Upload>
        </FormItem>
      </Form>
    </BasicModal>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, getCurrentInstance } from 'vue';
  import {
    Modal,
    Form,
    Input,
    FormItem,
    DatePicker,
    Upload,
    Select,
    SelectOption,
  } from 'ant-design-vue';
  import { BasicModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { fileUploadApi, fileViewApi } from '/@/api/projectManagement';
  import { useRoute } from 'vue-router';
  import { addAcontract, editAcontract } from '/@/api/api';
  const instance = getCurrentInstance();
  let route = useRoute();

  const { createMessage } = useMessage();

  const formRef = ref();
  const formState = reactive({
    projectId: '',
    amount: '',
    signDate: '',
    firstParty: '',
    licenseCompanyId: '',
    url: [],
    urlFile: '',
  });
  const allLicense = ref([]);
  let validatePass2 = () => {
    if (formState.url.length <= 0) {
      return Promise.reject('请上传附件');
    } else {
      return Promise.resolve();
    }
  };
  const rules = {
    amount: [{ required: true, message: '请输入合同金额' }],
    signDate: [{ required: true, message: '请选择签订时间' }],
    firstParty: [{ required: true, message: '请输入甲方' }],
    licenseCompanyId: [{ required: true, message: '请选择资质公司编号' }],
    url: [{ required: true, validator: validatePass2, trigger: 'change' }],
  };

  const beforeUpload = (file) => {
    let formData = new FormData();
    formData.append('file', file);
    fileUploadApi(formData).then((res) => {
      formState.url = [file];
      formState.urlFile = res;
      formRef.value.clearValidate('url');
    });

    return false;
  };
  const handleChange = (info) => {
    if (info.file.status == 'removed') {
      formState.url = [];
    }
  };

  const showContract = ref(false);
  const init = (data) => {
    console.log(data);
    showContract.value = true;
    allLicense.value = data.allLicense;
    formState.projectId = data.projectId;
    if (data.isEdit == true) {
      isEdit.value = true;
      editData.value = data.editData;
      console.log(editData.value);
      formState.amount = editData.value.contractResponse.amount;
      formState.signDate = editData.value.contractResponse.signDate;
      formState.firstParty = editData.value.contractResponse.firstParty;
      formState.licenseCompanyId = editData.value.contractResponse.licenseCompanyId;
      formState.urlFile = editData.value.contractResponse.url;
      fileViewApi(formState.urlFile).then((res) => {
        let nameExtension = formState.urlFile.split('.')[1];
        let file = new File([res], `合同附件.${nameExtension}`, { type: nameExtension }); // 创建一个File对象
        file.uid = 'v-' + Date.now();
        formState.url = [file];
        console.log(file, '图片');
      });
    } else {
      isEdit.value = false;
      editData.value = {};
      resetForm();
    }
  };
  const isEdit = ref(false);
  const editData = ref({});
  const onSubmit = () => {
    formRef.value
      .validate()
      .then(() => {
        if (isEdit.value == true) {
          editAcontract({
            ...formState,
            id: editData.value.contractResponse.id,
            url: formState.urlFile,
          }).then((res) => {
            if (res != false) {
              createMessage.success('编辑成功');
              isEdit.value = false;
              editData.value = {};
              if (instance) {
                instance.proxy?.$emit('tableNeedUpdate');
              }
              resetForm();
              showContract.value = false;
            }
          });
        } else {
          addAcontract({
            ...formState,
            url: formState.urlFile,
          }).then((res) => {
            if (res != false) {
              createMessage.success('添加成功');
              if (instance) {
                instance.proxy?.$emit('tableNeedUpdate');
              }
              resetForm();
              showContract.value = false;
            }
          });
        }
      })
      .catch((error: any) => {
        console.log('error', error);
      });
  };
  const resetForm = () => {
    formState.amount = '';
    formState.signDate = '';
    formState.firstParty = '';
    formState.licenseCompanyId = '';
    formState.url = [];
    formState.urlFile = '';
  };

  defineExpose({
    init,
  });
</script>
